<script setup lang="ts">
import { NImage } from 'naive-ui';
import { SvgIcon } from '@/components/common';
import { ref } from 'vue';

const props = defineProps<{
  src?: string;
  url?: string;
  width?: number | string;
  height?: number | string;
  preview?: boolean;
  previewDisabled?: boolean;
  class?: string;
}>();

const isLoading = ref(true);
const hasError = ref(false);

const handleLoad = () => {
  isLoading.value = false;
};

const handleError = () => {
  isLoading.value = false;
  hasError.value = true;
};

defineExpose({
  isLoading,
  hasError
});
</script>

<template>
  <div class="relative" :style="{ width: width, height: height }">
    <NImage
      :src="url || src"
      :width="width"
      :height="height"
      :preview="preview"
      :preview-disabled="previewDisabled"
      :class="class"
      @load="handleLoad"
      @error="handleError"
    >
      <template #placeholder>
        <div class="w-full h-full flex justify-center items-center bg-gray-100 dark:bg-gray-800">
          <SvgIcon icon="line-md:downloading-loop" class="text-[40px] text-green-300 animate-spin" />
        </div>
      </template>
    </NImage>

    <div v-if="hasError" class="absolute inset-0 flex justify-center items-center bg-gray-100 dark:bg-gray-800">
      <div class="text-center">
        <SvgIcon icon="mdi:image-off" class="text-[40px] text-gray-400" />
        <div class="text-sm text-gray-500 mt-2">图片加载失败</div>
      </div>
    </div>
  </div>
</template> 